﻿using ciji.Application.Dto;
using ciji.Core;
using Microsoft.Data.SqlClient;

namespace ciji.Application
{
    /// <summary>
    /// 鉴权
    /// </summary> 
    [ApiDescriptionSettings("登录鉴权", Order = 100, Description = "登录鉴权")]

    public class RBACService : IDynamicApiController, ITransient
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
        private SqlSugarRepository<cts_Employee> _employeeRep;
        private SqlSugarRepository<sys_LoginLog> _loginRep;
        private readonly ISysCacheService _cacheService;
        public RBACService(IHttpContextAccessor httpContextAccessor
            , SqlSugarRepository<cts_Employee> employeeRep
            , SqlSugarRepository<sys_LoginLog> loginRep
            , ISysCacheService cacheService)
        {
            _httpContextAccessor = httpContextAccessor;
            _employeeRep = employeeRep;
            _loginRep = loginRep;
            _cacheService = cacheService;
        }

        #region 登录
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost]
        public cts_Employee Login(LoginDto input)
        {

            var pwd = EncryptLibrary.MD5Encrypt(input.pwd, EncryptLibrary.getkey());
            var employee = _employeeRep.AsQueryable().Where(m => m.Account == input.account && m.Password == pwd).First();
            if (employee == null)
            {
                throw Oops.Bah("账号或密码不正确");
            }
            employee.Password = "";

            var authrule = new List<string>();
            if (employee.Auth == (employee.Auth | 1))
            {
                authrule.Add("user");
            }
            if (employee.Auth == (employee.Auth | 2))
            {
                authrule.Add("admin");
            }
            if (employee.Auth == (employee.Auth | 4))
            {
                authrule.Add("areaadmin");
            }
            if (employee.Auth == (employee.Auth | 32))
            {
                authrule.Add("superadmin");
            }
            employee.AuthRule = authrule;

            employee.Token = JWTEncryption.Encrypt(new Dictionary<string, object>()
            {

                { ClaimConst.UserId, employee.Gid },
                { ClaimConst.Account,employee.Account },
                { ClaimConst.Name, employee.EmployeeName },
                { ClaimConst.Auth, employee.Auth },
                { ClaimConst.UserAreaId, employee.AreaId },
                { ClaimConst.Timestamp, DateTimeOffset.Now.ToUnixTimeMilliseconds() },
            });
            string ip = _httpContextAccessor.HttpContext.GetRemoteIpAddressToIPv4();

            var loginLog = new sys_LoginLog()
            {
                LoginId = employee.Gid,
                LoginName = employee.EmployeeName,
                LoginIp = ip,
                LoginTime = DateTime.Now
            };

            _loginRep.Insert(loginLog);
            _httpContextAccessor.HttpContext.SigninToSwagger(employee.Token);
            _httpContextAccessor.HttpContext.Response.Headers["access-token"] = employee.Token;

            return employee;
        }



        /// <summary>
        /// 根据gid登录
        /// </summary>
        /// <param name="gid"></param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost]
        public cts_Employee LoginByGid(string gid)
        {
            if (!RedisHelper.Exists("Service_Gid_" + gid))
            {
                throw Oops.Bah("授权已过期");
            };
            var employee = _employeeRep.AsQueryable().Where(m => m.Gid == gid).First();
            if (employee == null)
            {
                throw Oops.Bah("账号或密码不正确");
            }
            employee.Password = "";

            var authrule = new List<string>();
            if (employee.Auth == (employee.Auth | 1))
            {
                authrule.Add("user");
            }
            if (employee.Auth == (employee.Auth | 2))
            {
                authrule.Add("admin");
            }
            if (employee.Auth == (employee.Auth | 4))
            {
                authrule.Add("areaadmin");
            }
            if (employee.Auth == (employee.Auth | 32))
            {
                authrule.Add("superadmin");
            }
            employee.AuthRule = authrule;

            employee.Token = JWTEncryption.Encrypt(new Dictionary<string, object>()
            {

                { ClaimConst.UserId, employee.Gid },
                { ClaimConst.Account,employee.Account },
                { ClaimConst.Name, employee.EmployeeName },
                { ClaimConst.UserAreaId, employee.AreaId },
                { ClaimConst.Timestamp, DateTimeOffset.Now.ToUnixTimeMilliseconds() },
            });
            string ip = _httpContextAccessor.HttpContext.GetRemoteIpAddressToIPv4();

            var loginLog = new sys_LoginLog()
            {
                LoginId = employee.Gid,
                LoginName = employee.EmployeeName,
                LoginIp = ip,
                LoginTime = DateTime.Now
            };

            _loginRep.Insert(loginLog);
            _httpContextAccessor.HttpContext.SigninToSwagger(employee.Token);
            _httpContextAccessor.HttpContext.Response.Headers["access-token"] = employee.Token;

            return employee;


        }
        #endregion

        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [LoggingMonitor]
        public int UpdatePwd(UpDatePwdDto input)
        {

            var employeeId = UserHelper.GetUserId();
            var oldPwd = EncryptLibrary.MD5Encrypt(input.oldpwd, EncryptLibrary.getkey());
            var employee = _employeeRep.GetFirst(m => m.Gid == employeeId && m.Password == oldPwd);
            if (employee == null)
            {
                throw Oops.Bah("原密码不正确");
            }
            employee.Password = EncryptLibrary.MD5Encrypt(input.newpwd, EncryptLibrary.getkey());
            return _employeeRep.AsUpdateable(employee).UpdateColumns(m => m.Password).ExecuteCommand();

        }
        /// <summary>
        /// 获取权限
        /// </summary>
        /// <returns></returns>
        [NonAction]
        public List<string> GetPermission()
        {
            var userId = UserHelper.GetUserId();
            var permissions = _cacheService.GetPermission(userId);
            if (permissions == null || permissions.Count == 0)
            {
                permissions = new List<string>();
                var employee = _employeeRep.GetFirst(m => m.Gid == userId);
                if (employee.Auth == (employee.Auth | 1))
                {
                    permissions.Add("user");
                }
                if (employee.Auth == (employee.Auth | 2))
                {
                    permissions.Add("admin");
                }
                if (employee.Auth == (employee.Auth | 32))
                {
                    permissions.Add("superadmin");
                }
                _cacheService.SetPermission(userId, permissions); // 缓存结果
            }
            return permissions;
        }
    }
}
